"""
智能判断工具
"""

import json
import logging
from typing import Dict, List, Any, Optional
from datetime import datetime
import asyncio

from .registry import register_tool
from ..features.intelligent_judgment import (
    RuleEngine, AnomalyData, LLMConfig, LLMJudgmentManager,
    IntelligentJudgmentCoordinator, JudgmentConfig, FinalJudgment
)
from ..cores.config import (
    LLM_API_URL, LLM_API_KEY, LLM_MODEL, LLM_MAX_TOKENS, LLM_TEMPERATURE,
    ENABLE_LLM_JUDGMENT, LLM_CONFIDENCE_THRESHOLD, RULE_PRIORITY_THRESHOLD,
    ENABLE_LEARNING, MAX_HISTORICAL_CONTEXT
)

logger = logging.getLogger(__name__)

# 全局智能判断协调器
_judgment_coordinator: Optional[IntelligentJudgmentCoordinator] = None

def _get_judgment_coordinator() -> IntelligentJudgmentCoordinator:
    """获取智能判断协调器实例"""
    global _judgment_coordinator
    
    if _judgment_coordinator is None:
        # 初始化规则引擎
        rule_engine = RuleEngine()
        
        # 初始化LLM管理器（如果启用）
        llm_manager = None
        if ENABLE_LLM_JUDGMENT and LLM_API_KEY:
            llm_config = LLMConfig(
                api_url=LLM_API_URL,
                api_key=LLM_API_KEY,
                model=LLM_MODEL,
                max_tokens=LLM_MAX_TOKENS,
                temperature=LLM_TEMPERATURE
            )
            llm_manager = LLMJudgmentManager(llm_config)
        
        # 配置判断协调器
        judgment_config = JudgmentConfig(
            enable_llm=ENABLE_LLM_JUDGMENT,
            llm_confidence_threshold=LLM_CONFIDENCE_THRESHOLD,
            rule_priority_threshold=RULE_PRIORITY_THRESHOLD,
            enable_learning=ENABLE_LEARNING,
            max_historical_context=MAX_HISTORICAL_CONTEXT
        )
        
        _judgment_coordinator = IntelligentJudgmentCoordinator(
            rule_engine=rule_engine,
            llm_manager=llm_manager,
            config=judgment_config
        )
        
        logger.info("智能判断协调器初始化完成")
    
    return _judgment_coordinator

async def intelligent_judge_anomaly_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """智能判断异常"""
    try:
        # 获取异常数据
        anomaly_data = arguments.get("anomaly_data", {})
        system_context = arguments.get("system_context", {})
        
        # 创建AnomalyData对象
        anomaly = AnomalyData(
            severity=float(anomaly_data.get("severity", 0)),
            duration=int(anomaly_data.get("duration", 0)),
            error_frequency=float(anomaly_data.get("error_frequency", 0)),
            business_impact=float(anomaly_data.get("business_impact", 0)),
            affected_services=int(anomaly_data.get("affected_services", 0)),
            timestamp=datetime.fromisoformat(anomaly_data.get("timestamp", datetime.now().isoformat())),
            service_name=anomaly_data.get("service_name", ""),
            metric_name=anomaly_data.get("metric_name", ""),
            current_value=float(anomaly_data.get("current_value", 0)),
            threshold=float(anomaly_data.get("threshold", 0))
        )
        
        # 获取协调器并执行判断
        coordinator = _get_judgment_coordinator()
        judgment = await coordinator.judge_anomaly(anomaly, system_context)
        
        # 记录结果
        coordinator.record_judgment_result(judgment, anomaly, success=True)
        
        # 返回结果
        result = {
            "action": judgment.action.value,
            "confidence": judgment.confidence,
            "reasoning": judgment.reasoning,
            "source": judgment.source,
            "detailed_analysis": judgment.detailed_analysis,
            "suggested_actions": judgment.suggested_actions,
            "risk_assessment": judgment.risk_assessment,
            "auto_fix_script": judgment.auto_fix_script
        }
        
        logger.info(f"智能判断完成: {judgment.action.value} - 置信度: {judgment.confidence}")
        return [{"text": json.dumps(result, ensure_ascii=False, indent=2)}]
        
    except Exception as e:
        logger.error(f"智能判断失败: {e}")
        return [{"text": f"❌ 智能判断失败: {str(e)}"}]

async def batch_judge_anomalies_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """批量判断异常"""
    try:
        # 获取异常数据列表
        anomalies_data = arguments.get("anomalies", [])
        system_context = arguments.get("system_context", {})
        
        # 创建AnomalyData对象列表
        anomalies = []
        for data in anomalies_data:
            anomaly = AnomalyData(
                severity=float(data.get("severity", 0)),
                duration=int(data.get("duration", 0)),
                error_frequency=float(data.get("error_frequency", 0)),
                business_impact=float(data.get("business_impact", 0)),
                affected_services=int(data.get("affected_services", 0)),
                timestamp=datetime.fromisoformat(data.get("timestamp", datetime.now().isoformat())),
                service_name=data.get("service_name", ""),
                metric_name=data.get("metric_name", ""),
                current_value=float(data.get("current_value", 0)),
                threshold=float(data.get("threshold", 0))
            )
            anomalies.append(anomaly)
        
        # 获取协调器并执行批量判断
        coordinator = _get_judgment_coordinator()
        judgments = await coordinator.batch_judge(anomalies, system_context)
        
        # 记录结果
        for judgment, anomaly in zip(judgments, anomalies):
            coordinator.record_judgment_result(judgment, anomaly, success=True)
        
        # 返回结果
        results = []
        for i, judgment in enumerate(judgments):
            result = {
                "index": i,
                "service": anomalies[i].service_name,
                "metric": anomalies[i].metric_name,
                "action": judgment.action.value,
                "confidence": judgment.confidence,
                "reasoning": judgment.reasoning,
                "source": judgment.source
            }
            results.append(result)
        
        logger.info(f"批量判断完成: {len(judgments)} 个异常")
        return [{"text": json.dumps(results, ensure_ascii=False, indent=2)}]
        
    except Exception as e:
        logger.error(f"批量判断失败: {e}")
        return [{"text": f"❌ 批量判断失败: {str(e)}"}]

async def add_custom_rule_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """添加自定义规则"""
    try:
        rule_data = arguments.get("rule", {})
        
        # 创建规则
        rule = {
            "name": rule_data.get("name", "custom_rule"),
            "condition": lambda data: eval(rule_data.get("condition", "True")),  # 注意：这里简化处理
            "action": getattr(AnomalyData, rule_data.get("action", "MANUAL_REVIEW")),
            "level": getattr(AnomalyData, rule_data.get("level", "ALERT")),
            "confidence": float(rule_data.get("confidence", 0.7)),
            "reasoning": rule_data.get("reasoning", "自定义规则")
        }
        
        # 添加到规则引擎
        coordinator = _get_judgment_coordinator()
        coordinator.rule_engine.add_rule(rule)
        
        logger.info(f"添加自定义规则: {rule['name']}")
        return [{"text": f"✅ 成功添加自定义规则: {rule['name']}"}]
        
    except Exception as e:
        logger.error(f"添加自定义规则失败: {e}")
        return [{"text": f"❌ 添加自定义规则失败: {str(e)}"}]

async def get_judgment_statistics_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """获取判断统计信息"""
    try:
        coordinator = _get_judgment_coordinator()
        
        # 计算统计信息
        total_judgments = len(coordinator.historical_judgments)
        if total_judgments == 0:
            return [{"text": "暂无判断记录"}]
        
        # 按动作类型统计
        action_stats = {}
        source_stats = {}
        success_count = 0
        
        for judgment in coordinator.historical_judgments:
            action = judgment.get("action", "unknown")
            source = judgment.get("source", "unknown")
            success = judgment.get("success", True)
            
            action_stats[action] = action_stats.get(action, 0) + 1
            source_stats[source] = source_stats.get(source, 0) + 1
            if success:
                success_count += 1
        
        # 计算成功率
        success_rate = success_count / total_judgments
        
        # 构建统计结果
        stats = {
            "total_judgments": total_judgments,
            "success_rate": f"{success_rate:.2%}",
            "action_distribution": action_stats,
            "source_distribution": source_stats,
            "recent_judgments": coordinator.historical_judgments[-10:]  # 最近10条
        }
        
        logger.info(f"获取判断统计信息: {total_judgments} 条记录")
        return [{"text": json.dumps(stats, ensure_ascii=False, indent=2)}]
        
    except Exception as e:
        logger.error(f"获取判断统计信息失败: {e}")
        return [{"text": f"❌ 获取判断统计信息失败: {str(e)}"}]

# 注册工具
register_tool(
    "intelligent_judge_anomaly",
    "智能判断异常并决定处理方式",
    {
        "type": "object",
        "properties": {
            "anomaly_data": {
                "type": "object",
                "description": "异常数据",
                "properties": {
                    "severity": {"type": "number", "description": "严重度 (0-10)"},
                    "duration": {"type": "integer", "description": "持续时间(分钟)"},
                    "error_frequency": {"type": "number", "description": "错误频率"},
                    "business_impact": {"type": "number", "description": "业务影响 (0-10)"},
                    "affected_services": {"type": "integer", "description": "受影响服务数量"},
                    "timestamp": {"type": "string", "description": "时间戳 (ISO格式)"},
                    "service_name": {"type": "string", "description": "服务名称"},
                    "metric_name": {"type": "string", "description": "指标名称"},
                    "current_value": {"type": "number", "description": "当前值"},
                    "threshold": {"type": "number", "description": "阈值"}
                },
                "required": ["severity", "duration", "error_frequency", "business_impact", "affected_services", "service_name", "metric_name", "current_value", "threshold"]
            },
            "system_context": {
                "type": "object",
                "description": "系统上下文信息"
            }
        },
        "required": ["anomaly_data"]
    },
    intelligent_judge_anomaly_impl
)

register_tool(
    "batch_judge_anomalies",
    "批量智能判断异常",
    {
        "type": "object",
        "properties": {
            "anomalies": {
                "type": "array",
                "description": "异常数据列表",
                "items": {
                    "type": "object",
                    "properties": {
                        "severity": {"type": "number"},
                        "duration": {"type": "integer"},
                        "error_frequency": {"type": "number"},
                        "business_impact": {"type": "number"},
                        "affected_services": {"type": "integer"},
                        "timestamp": {"type": "string"},
                        "service_name": {"type": "string"},
                        "metric_name": {"type": "string"},
                        "current_value": {"type": "number"},
                        "threshold": {"type": "number"}
                    }
                }
            },
            "system_context": {
                "type": "object",
                "description": "系统上下文信息"
            }
        },
        "required": ["anomalies"]
    },
    batch_judge_anomalies_impl
)

register_tool(
    "add_custom_rule",
    "添加自定义判断规则",
    {
        "type": "object",
        "properties": {
            "rule": {
                "type": "object",
                "description": "规则定义",
                "properties": {
                    "name": {"type": "string", "description": "规则名称"},
                    "condition": {"type": "string", "description": "条件表达式"},
                    "action": {"type": "string", "description": "动作类型"},
                    "level": {"type": "string", "description": "异常等级"},
                    "confidence": {"type": "number", "description": "置信度"},
                    "reasoning": {"type": "string", "description": "判断理由"}
                },
                "required": ["name", "action", "confidence", "reasoning"]
            }
        },
        "required": ["rule"]
    },
    add_custom_rule_impl
)

register_tool(
    "get_judgment_statistics",
    "获取智能判断统计信息",
    {
        "type": "object",
        "properties": {}
    },
    get_judgment_statistics_impl
) 